<?php
namespace dahantong;
class SmsSDK {
	private $accountSid; //帐号ID
	private $authToken;	 //授权令牌
	private $appId;	//应用ID
	private $apiUrl; //API请求路径
	private $smsUrl = "{apiUrl}API/sendMessage?sig={sig}"; //短信API路径
	private $intsmsUrl = "{apiUrl}api/intsms?sig={sig}"; //短信API路径
	private $logFile = "log.txt"; // 日志文件
	private $logOn = true; // true：开启日志， false：关闭日志，默认开启
	private $logHandle; //log文件句柄
	private $timeStamp; //时间戳
	
	function __construct() {
		$this->logHandle = fopen($this->logFile, 'a');
		$this->timeStamp = date("YmdHis");
	}
    
    public function setAccountSid($accountSid) {
      	$this->accountSid = $accountSid; 
    }
    
    public function setAuthToken($authToken) {
      	$this->authToken = $authToken;   
    }
    
    public function setAppId($appId) {
     	$this->appId = $appId;    
    }
    
    public function setApiUrl($apiUrl) {
      	$this->apiUrl = $apiUrl;   
    }
    
    // 开启或关闭日志
    public function setLogOn($logOn) {
    	$this->logOn = $logOn;
    }
    
    private function log($log) {
      	if(!$this->logOn) return;
     	fwrite($this->logHandle, $log."\n");
    }
    
    private function checkConfig() {    
        if($this->accountSid == ""){
          	return $this->getStatusData('000017', 'AccountSid为空');
        }
        
        if($this->authToken == ""){
          	return $this->getStatusData('000018', 'Auth Token为空');
        }
        
        if($this->appId == ""){
          	return $this->getStatusData('000016', '应用ID为空');
        }   
        
        if($this->apiUrl == ""){
          	return $this->getStatusData('000019', 'API URL为空');
        }
        
        return "";
    }
    
    private function checkRequest($to, $tempId) {    
        if($to == ""){
          	return $this->getStatusData('000006', '接收短信的手机号码为空');
        }
        
        if($tempId == ""){
          	return $this->getStatusData('000008', '短信模板为空或未设置');
        }
        
        return "";
    }
    
    private function getStatusData($code, $msg) {
    	 $data = new stdClass();
         $data->statusCode = $code;
         $data->statusMsg = $msg;
         
         return $data;
    }
    
    private function buildRequestUrl() {
        $sig = strtoupper(md5($this->accountSid . $this->authToken . $this->timeStamp));
        $url = str_replace("{sig}", $sig, $this->smsUrl);
        $url = str_replace("{apiUrl}", $this->apiUrl, $url);
        
        return $url;
    }
	
	 private function buildintsmsRequestUrl() {
        $sig = strtoupper(md5($this->accountSid . $this->authToken . $this->timeStamp));
        $url = str_replace("{sig}", $sig, $this->intsmsUrl);
        $url = str_replace("{apiUrl}", $this->apiUrl, $url);
        
        return $url;
    }
	
    
    private function buildRequestHeader() {
        $auth = base64_encode($this->accountSid . ":" . $this->timeStamp);
        $header = array("Accept:application/json",
        				"Content-Type:application/json;charset=utf-8",
        				"Authorization:$auth");
        				
        return $header;
    }
   	
   	private function buildRequestBody($to, $tempId, $datas) {
	    $value = "";
	    
	    $len = count($datas);
	    for($i = 0; $i < $len; $i++){
	       $value = $value . "'" . $datas[$i] . "'"; 
	       if($i < ($len - 1)){
	          $value = $value . ",";
	       }
	    }
	    
	    $body = "{'to':'$to','templateId':'$tempId','appId':'$this->appId','datas':[".$value."]}";

        return $body;
   	}
   	
   	// HTTP POST请求
    private function http_post($url, $header, $data) {
       $ci = curl_init();
       curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
       curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ci, CURLOPT_HEADER, false);
       curl_setopt($ci, CURLOPT_POST, true);
       curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ci, CURLOPT_URL, $url);
       curl_setopt($ci, CURLOPT_HTTPHEADER, $header);
       curl_setopt($ci, CURLOPT_POSTFIELDS, $data);
       $result = curl_exec($ci);
       
       if($result == NULL) {
          echo "http request error  <br/>"; 
          $result = "{\"statusCode\":\"000010\", \"statusMsg\":\"服务器请求出错，请确认参数是否正确，如无法解决，请联系工作人员\"}";
       }

       curl_close($ci);
       return $result;
     }
     
    /**
    * 发送短信
    * @param to 接收手机号码
    * @param tempId 模板ID
    * @param datas 内容数据
    */       
    public function sendSMS($to, $tempId, $datas) {
        // 检查配置参数
        $config = $this->checkConfig();
        if($config != "") return $config;
        
        // 检查请求参数
        $req = $this->checkRequest($to, $tempId);
        if($req != "") return $req;
 		
        // 生成请求参数
        $url = $this->buildRequestUrl();
        $header = $this->buildRequestHeader();
        $body = $this->buildRequestBody($to, $tempId, $datas);
        $this->log("--- Start to send SMS ---");
        $this->log("url: $url");
        $this->log("header: " . implode(' ', $header));
        $this->log("body: $body");
        
        // 调用平台短信接口
        $result = $this->http_post($url, $header, $body);
		$this->log("response result: " . $result);
		//echo "response result: $result <br/>";
		
        return json_decode($result);
    }
	
	/**
    * 发送国际短信
    * @param to 接收手机号码
    * @param tempId 模板ID
    * @param datas 内容数据
    */       
    public function sendINTSMS($to, $tempId, $datas) {
        // 检查配置参数
        $config = $this->checkConfig();
        if($config != "") return $config;
        
        // 检查请求参数
        $req = $this->checkRequest($to, $tempId);
        if($req != "") return $req;
 		
        // 生成请求参数
        $url = $this->buildintsmsRequestUrl();
        $header = $this->buildRequestHeader();
        $body = $this->buildRequestBody($to, $tempId, $datas);
        $this->log("--- Start to send SMS ---");
        $this->log("url: $url");
        $this->log("header: " . implode(' ', $header));
        $this->log("body: $body");
        
        // 调用平台短信接口
        $result = $this->http_post($url, $header, $body);
		$this->log("response result: " . $result);
		//echo "response result: $result <br/>";
		
        return json_decode($result);
    }
   
}
?>
